#include "adc_dma.h"

static uint16_t adc_value;

void adc_dma_init()
{
	/* Initialize the gpio */
	GPIO_InitType GPIO_InitStruct;
	
	RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOC, ENABLE);
	
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AIN;
	GPIO_InitStruct.Pin = GPIO_PIN_0;
	GPIO_InitPeripheral(GPIOC, &GPIO_InitStruct);
	
	/* Initialize the dma */
	DMA_InitType DMA_InitStruct;
	
	RCC_EnableAHBPeriphClk(RCC_AHB_PERIPH_DMA1, ENABLE);
	
	DMA_InitStruct.PeriphAddr     = (uint32_t)&ADC1->DAT;
	DMA_InitStruct.MemAddr        = (uint32_t)&adc_value;
	DMA_InitStruct.Direction      = DMA_DIR_PERIPH_SRC;
	DMA_InitStruct.BufSize        = 1;
	DMA_InitStruct.PeriphInc      = DMA_PERIPH_INC_DISABLE;
	DMA_InitStruct.DMA_MemoryInc  = DMA_MEM_INC_DISABLE;
	DMA_InitStruct.PeriphDataSize = DMA_PERIPH_DATA_SIZE_HALFWORD;
	DMA_InitStruct.MemDataSize    = DMA_MemoryDataSize_HalfWord;
	DMA_InitStruct.CircularMode   = DMA_MODE_CIRCULAR;
	DMA_InitStruct.Priority       = DMA_PRIORITY_HIGH;
	DMA_InitStruct.Mem2Mem        = DMA_M2M_DISABLE;
	DMA_Init(DMA1_CH1, &DMA_InitStruct);
	DMA_EnableChannel(DMA1_CH1, ENABLE);
	
	/* Initialize the adc */
	ADC_InitType ADC_InitStruct;
	
	ADC_ConfigClk(ADC_CTRL3_CKMOD_AHB, RCC_ADCHCLK_DIV4);
	RCC_EnableAHBPeriphClk(RCC_AHB_PERIPH_ADC1, ENABLE);
	
	ADC_InitStruct.WorkMode       = ADC_WORKMODE_INDEPENDENT;
	ADC_InitStruct.MultiChEn      = DISABLE;
	ADC_InitStruct.ContinueConvEn = ENABLE;
	ADC_InitStruct.ExtTrigSelect  = ADC_EXT_TRIGCONV_NONE;
	ADC_InitStruct.DatAlign       = ADC_DAT_ALIGN_R;
	ADC_InitStruct.ChsNumber      = 1;
	ADC_Init(ADC1, &ADC_InitStruct);
	/* ADC1 regular channel14 configuration */
	ADC_ConfigRegularChannel(ADC1, ADC1_Channel_06_PC0, 1, ADC_SAMP_TIME_55CYCLES5);
	/* Enable ADC1 DMA */
	ADC_EnableDMA(ADC1, ENABLE);
	/* Enable ADC1 */
	ADC_Enable(ADC1, ENABLE);
	
}

uint16_t adc_get_sample_value()
{
	/* Check ADC Ready */
	while(ADC_GetFlagStatusNew(ADC1,ADC_FLAG_RDY) == RESET)
	{
		;
	}
	/* Start ADC1 calibration */
	ADC_StartCalibration(ADC1);
	/* Check the end of ADC1 calibration */
	while (ADC_GetCalibrationStatus(ADC1) == SET)
	{
		;
	}
	ADC_EnableSoftwareStartConv(ADC1, ENABLE);
	return adc_value;
}


